#include <bits/stdc++.h>
using namespace std;
const int N = 20;
int n, m, a[N][N];
vector<int> f1[N], f2[N];
signed main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < n; ++j)
      scanf("%d", &a[i][j]);
  for (int i = 0; i < (1 << (n - 1)); ++i) {
    int x = n - 1, y = n - 1, bs = 1, res = 0;
    for (int j = 0; j < n - 1; ++j) {
      res = (res + a[x][y] * 111 * bs) % m;
      bs = bs * 1011 % m;
      if ((i >> j) & 1)
        y--;
      else
        x--;
    }

    res = (res + a[x][y] * 111 * bs) % m;
    f2[y].push_back(res);
  }

  int bs = 1;
  for (int i = 0; i < n; ++i)
    bs = bs * 1011 % m;

  for (int i = 0; i < (1 << (n - 1)); ++i) {
    int x = 0, y = 0, res = 0;
    for (int j = 0; j < n - 1; ++j) {
      res = (res * 1011 + a[x][y]) % m;
      if ((i >> j) & 1)
        y++;
      else
        x++;
    }
    f1[y].push_back(res * 111 * bs % m);
  }

  int ans = 0;
  for (int i = 0; i < n; ++i) {

    sort(f1[i].begin(), f1[i].end());
    sort(f2[i].begin(), f2[i].end());
    int len1 = (int)f1[i].size();
    int len2 = (int)f2[i].size();
    for (int j = 0, k = len2 - 1; j < len1; ++j) {

      while (k >= 0 && f2[i][k] + f1[i][j] >= m)
        --k;
      if (k >= 0)
        ans = max(ans, f1[i][j] + f2[i][k]);
    }
    ans = max(ans, f1[i][len1 - 1] + f2[i][len2 - 1] - m);
  }

  printf("%d\n", ans);
  return 0;
}